<template>
  <div class="comment-list">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input
            v-model="searchForm.content"
            placeholder="请输入评论内容"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="评论类型">
          <el-select
            v-model="searchForm.commentType"
            placeholder="请选择评论类型"
            clearable
            style="width: 150px"
          >
            <el-option label="文档评论" value="document" />
            <el-option label="案件评论" value="case" />
          </el-select>
        </el-form-item>
        <el-form-item label="回复层级">
          <el-select
            v-model="searchForm.replyLevel"
            placeholder="请选择层级"
            clearable
            style="width: 120px"
          >
            <el-option label="顶级评论" value="top" />
            <el-option label="回复评论" value="reply" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="action-section">
      <el-alert
        title="评论管理仅支持查看和删除操作，不支持新增和编辑"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'replies', hasChildren: 'hasReplies' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.userAvatar" :size="30" class="user-avatar">
                {{ row.username?.charAt(0) }}
              </el-avatar>
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="评论对象" width="200">
          <template #default="{ row }">
            <div v-if="row.documentTitle" class="comment-target">
              <el-tag type="primary" size="small">文档</el-tag>
              <span class="target-title">{{ row.documentTitle }}</span>
            </div>
            <div v-else-if="row.caseNumber" class="comment-target">
              <el-tag type="warning" size="small">案件</el-tag>
              <span class="target-title">{{ row.caseNumber }}</span>
            </div>
            <span v-else class="no-target">无关联对象</span>
          </template>
        </el-table-column>
        <el-table-column label="层级" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.parentId" type="info" size="small">
              回复
            </el-tag>
            <el-tag v-else type="success" size="small">
              顶级
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <CommentDetail
      v-model:visible="detailVisible"
      :comment-id="currentCommentId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getCommentPage, deleteComment } from '../../api/comment'
import CommentDetail from './components/CommentDetail.vue'

// 搜索表单
const searchForm = reactive({
  username: '',
  content: '',
  commentType: null,
  replyLevel: null
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 对话框状态
const detailVisible = ref(false)
const currentCommentId = ref(null)

// 获取评论列表
const fetchCommentList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 处理评论类型
    if (searchForm.commentType === 'document') {
      delete params.commentType
      // 可以添加额外的过滤逻辑
    } else if (searchForm.commentType === 'case') {
      delete params.commentType
      // 可以添加额外的过滤逻辑
    }
    
    // 处理回复层级
    if (searchForm.replyLevel === 'top') {
      params.parentId = null
    } else if (searchForm.replyLevel === 'reply') {
      // 这里可能需要特殊处理
    }
    delete params.replyLevel
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getCommentPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchCommentList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    content: '',
    commentType: null,
    replyLevel: null
  })
  pagination.pageNum = 1
  fetchCommentList()
}

// 详情
const handleDetail = (row) => {
  currentCommentId.value = row.id
  detailVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条评论吗？`,
      '确认删除',
      {
        type: 'warning'
      }
    )

    const response = await deleteComment(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchCommentList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = () => {
  pagination.pageNum = 1
  fetchCommentList()
}

// 当前页改变
const handleCurrentChange = () => {
  fetchCommentList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCommentList()
})
</script>

<style scoped>
.comment-list {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  font-size: 12px;
}

.username {
  font-size: 14px;
  color: #333;
}

.comment-target {
  display: flex;
  align-items: center;
  gap: 8px;
}

.target-title {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 120px;
}

.no-target {
  color: #999;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-list {
    padding: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }
  
  .user-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .comment-target {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>
